import requests
from urllib import parse
import time
import json
import urllib3

urllib3.disable_warnings()


class XHS660(object):
    def __init__(self, deviceId, fid, device_fingerprint, sid):
        self.proxies = None
        self.ENCRYPT_URL = "http://120.53.131.28:18283/660"
        self.TOKEN = "5e7c58a4d651d470c080b27a61320148"
        self.USER_AGENT = "Dalvik/2.1.0 (Linux; U; Android 5.0.2; Samsung Note3 Build/LMY47X) Resolution/1080*1920 Version/6.60.0 Build/6600125 Device/(samsung;Samsung Note3)"
        self.deviceId = deviceId
        self.fid = fid
        self.device_fingerprint = device_fingerprint
        self.sid = sid
        self.xy_ter_str = self.get_ter_str()


    def __get_xy_common_params(self):
        return "platform=android&deviceId={deviceId}&version=6.60&build=6600125&t=1592222248&identifier_flag=1&fid={fid}&device_fingerprint={device_fingerprint}&sid={sid}".format(
            deviceId=self.deviceId,
            fid=self.fid,
            device_fingerprint=self.device_fingerprint,
            sid=self.sid,
        )
    def __get_xy_platform_info(self):
        return "platform=android&version=6.60&build=6600125&deviceId={deviceId}&bundle=com.xingin.discover".format(
            deviceId=self.deviceId,
        )


    def __append_url_params(self, url, query_params):
        params = parse.urlencode(query_params)
        if not url.__contains__('?'):
            url = url + '?'

        if url.endswith('?') or url.endswith('&'):
            url = url + params
        else:
            url = url + '&' + params
        return url

    def get_ter_str(self):
        """
        deviceId=353CE2F-0131-474E-A093-DF39D12E4515&device_fingerprint=202006261454019d1b1a0db8172b59cbe25925c1c3900001ab4b27b14c4883&device_fingerprint1=202006261454019d1b1a0db8172b59cbe25925c1c3900001ab4b27b14c4883&
        fid=1595172589-0-0-2de0b0d2666328142e712e63c19fad35
        &lang=zh&platform=android&sid=session.1593665994331207470119&sign=b1c352302484d97e6e9c93f7334a2720&t=1592222248
        :return:
        """
        url = "https://www.xiaohongshu.com/api/sns/v3/user/me?"
        query_params = {
            "deviceId": self.deviceId,
            "device_fingerprint": self.device_fingerprint,
            "device_fingerprint1": self.device_fingerprint,
            "fid": self.fid,
            "lang": "zh",
            "platform": "android",
            "sid": self.sid,
            "t": int(time.time())
        }
        url = self.__append_url_params(url, query_params)

        header = {
            "User-Agent": self.USER_AGENT,
            "xy-common-params": self.__get_xy_common_params(),
            "xy-platform-info": self.__get_xy_platform_info(),
            "shield": ""
        }

        response = requests.get(url, headers=header, proxies=self.proxies, verify=False)

        xy_ter_str = response.headers["xy-ter-str"]
        return xy_ter_str

    def test_get(self):
        xy_common_params = self.__get_xy_common_params()
        xy_platform_info = self.__get_xy_platform_info()
        # url = "https://www.xiaohongshu.com/api/sns/v3/user/me?deviceId=353CE2F-0131-474E-A093-DF39D12E4515&device_fingerprint=202006261454019d1b1a0db8172b59cbe25925c1c3900001ab4b27b14c4883&device_fingerprint1=202006261454019d1b1a0db8172b59cbe25925c1c3900001ab4b27b14c4883&fid=1595172589-0-0-2de0b0d2666328142e712e63c19fad35&lang=zh&platform=android&sid=session.1593665994331207470119&t=1592222248"
        # url = "https://www.xiaohongshu.com/api/sns/v3/user/me?"
        url = "https://www.xiaohongshu.com/api/sns/v6/homefeed?oid=homefeed_recommend&"
        query_params = {
            "deviceId": self.deviceId,
            "device_fingerprint": self.device_fingerprint,
            "device_fingerprint1": self.device_fingerprint,
            "fid": self.fid,
            "lang": "zh",
            "platform": "android",
            "sid": self.sid,
            "t": int(time.time())
        }
        url = self.__append_url_params(url, query_params)
        data = {
            "token": self.TOKEN,
            "url": url,
            "xy-common-params": xy_common_params,
            "xy-platform-info": xy_platform_info,
            "xy-ter-str": self.xy_ter_str,
            "body": ""  # GET 请求不需要 body 参数
        }

        ret = requests.post(self.ENCRYPT_URL, data=data, proxies=self.proxies).json()
        if ret["code"] == 1000:
            header = {
                "User-Agent": self.USER_AGENT,
                "xy-common-params": xy_common_params,
                "xy-platform-info": xy_platform_info,
                "shield": ret["data"]["shield"]
            }
            ret = requests.get(url, headers=header, proxies=self.proxies, verify=False).json()
            print(json.dumps(ret, ensure_ascii=False))
        else:
            print(json.dumps(ret, ensure_ascii=False))


if __name__ == '__main__':
    data = {"device_id": "76976ec9-bbf2-4349-9b46-ce53d84172fb", "smid": "20200921120224aaebbe693878ef37846ce0a0046b2c090117d975f90a316a", "sid": "session.1600660949641772576652", "fid": "1600660939107afc719fd3f889f41bd1d8e19b501af7", "crypt_method": "0ad1038dcfee51c9"}
    deviceId = data['device_id']
    device_fingerprint = data['smid']
    sid = data['sid']
    fid = data['fid']
    obj = XHS660(deviceId, fid, device_fingerprint, sid)
    obj.test_get()